#!c:/perl/bin/perl.exe

use DBI;
use DBD::mysql;
use DIVA_DB;
use WWCOM;
use CGI;
use strict;
	
my $DEBUG= 1;
$DIVA_DB::DEBUG= $DEBUG;

$DIVA_DB::DATABASE_NAME= "wwcom";
$DIVA_DB::DATABASE_SERVER= "localhost:3306";

my $cgi= new CGI;
my %outvars;

my @names= <$WWCOM::NEWSDIR/*.news>;
@names= sort {
	$a=~ /.*\/[0-9]+\.[0-9]+\.([0-9]{2})\-([0-9]{2})\-([0-9]{4})\.([0-9]{2})\-([0-9]{2})\-([0-9]{4})\.*/;
	my $newesta= $6.$5.$4;
	$b=~ /.*\/[0-9]+\.[0-9]+\.([0-9]{2})\-([0-9]{2})\-([0-9]{4})\.([0-9]{2})\-([0-9]{2})\-([0-9]{4})\.*/;
	my $newestb= $6.$5.$4;
	$newesta <=> $newestb;} @names; #sort files by content date

my %allstories;
my $cols= ['STORY_TITLE','STORY_BODY','STORY_AUTHOR','STORY_URL','STORY_SITE','STORY_SITEURL','FK_OBJECT_ID'];
my $vals;

my $dbh= &DIVA_DB::DB_CONNECT('wwcom','wwcom');
for(my $i= 0; $i<$#names; $i++) {
	print "File: $names[$i]\n";
	my %storyhash= &WWCOM::READFILE($names[$i]);
	$vals= [];
	my $count= 0;
	
	foreach my $key (keys %storyhash) {
		print "\tStory: $key - $storyhash{$key}{'title'}\n";
		$allstories{$key}= $storyhash{$key};
		$$vals[$count][0]= &DIVA_DB::DECODE($storyhash{$key}{'title'});
		my $date= &DIVA_DB::DECODE($storyhash{$key}{'date'});
		$date=~ /([0-9]+)\.([\d]+)\.([\d]+)/;
		my $db_date= "$3-$2-$1";
		if ($db_date eq '--') {
			$db_date= '0000-00-00';
		}
		print "\t** $date: $db_date\n";
		$$vals[$count][1]= &DIVA_DB::DECODE($storyhash{$key}{'text'});
		$$vals[$count][2]= &DIVA_DB::DECODE($storyhash{$key}{'author'});
		$$vals[$count][3]= &DIVA_DB::DECODE($storyhash{$key}{'url'});
		$$vals[$count][4]= &DIVA_DB::DECODE($storyhash{$key}{'site'});
		$$vals[$count][5]= &DIVA_DB::DECODE($storyhash{$key}{'siteurl'});
		#$$vals[$count][6]= $key;
		#$count++;
		&DIVA_DB::INSERT_DATA($dbh,$cgi,\%outvars,'OBJECT',['FK_CONTENTTYPE_ID','OBJECT_DATE'],[[1,$db_date]]);
		$$vals[$count][6]= $dbh->{'mysql_insertid'};
		$allstories{$key}{'FK_OBJECT_ID'}= $dbh->{'mysql_insertid'};
		&DIVA_DB::INSERT_DATA($dbh,$cgi,\%outvars,'STORY',$cols,$vals);
		$allstories{$key}{'PK_STORY_ID'}= $dbh->{'mysql_insertid'};
	}
}
	
#now do threads
my %threads;
foreach my $key (keys %allstories) {
	$key=~ /^([\d]+)\.([\d\.]+)$/;
	my $tno= "$1.1";
	if (!exists $allstories{$tno}) {
		&DIVA_DB::UPDATE_DATA($dbh,$cgi,\%outvars,'OBJECT',['FK_HEAD_ID','FK_PARENT_ID'],[$allstories{$tno}{'FK_OBJECT_ID'},$allstories{$key}{'FK_OBJECT_ID'}],
			"PK_OBJECT_ID = $allstories{$key}{'FK_OBJECT_ID'}");
	}
}
	
	exit(0);
	
# now do relationships    
foreach my $key (keys %allstories) {
	if ($allstories{$key}{'relatedthreadtitles'} ne "") {
		print "Related: $key - $allstories{$key}{'relatedthreads'}\n";
	}
}
	
$dbh->disconnect; 